<template>
  <div class="history">
<<<<<<< HEAD
    <!-- 使用全局Header组件 -->
    <GlobalHeader 
      title="历史数据" 
      subtitle="查看和分析历史传感器数据，支持多种时间范围和数据筛选"
      :breadcrumbItems="[{ title: '历史数据', path: '/history' }]"
    >
      <template #actions>
        <el-button size="small" @click="exportData" :disabled="!hasData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </template>
    </GlobalHeader>

=======
>>>>>>> 8812a9148e94551207e748afbba84869577bb3db
    <!-- 数据筛选器 -->
    <el-card class="filter-card" shadow="hover">
      <template #header>
        <div class="filter-header">
          <span>数据筛选</span>
          <el-button size="small" @click="resetFilters">
            <el-icon><Refresh /></el-icon>
            重置筛选
          </el-button>
        </div>
      </template>
      <el-form :model="filters" label-width="100px" class="filter-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="时间范围">
              <el-select 
                v-model="filters.timeRange" 
                @change="handleTimeRangeChange"
                :popper-options="{ boundariesPadding: 0, gpuAcceleration: false }"
                popper-class="time-range-dropdown"
              >
                <el-option-group label="小时">
                  <el-option label="最近1小时" value="1h" />
                  <el-option label="最近6小时" value="6h" />
                  <el-option label="最近12小时" value="12h" />
                  <el-option label="最近24小时" value="24h" />
                </el-option-group>
                <el-option-group label="天">
                  <el-option label="最近3天" value="3d" />
                  <el-option label="最近7天" value="7d" />
                  <el-option label="最近30天" value="30d" />
                </el-option-group>
                <el-option-group label="长时间">
                  <el-option label="最近3个月" value="3m" />
                  <el-option label="最近6个月" value="6m" />
                  <el-option label="最近1年" value="1y" />
                </el-option-group>
                <el-option-group label="其他">
                  <el-option label="自定义" value="custom" />
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-if="filters.timeRange === 'custom'">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="filters.startTime"
                type="datetime"
                placeholder="选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-if="filters.timeRange === 'custom'">
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="filters.endTime"
                type="datetime"
                placeholder="选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="数据类型">
              <el-select v-model="filters.dataType" multiple placeholder="选择数据类型">
                <el-option label="温度" value="temperature" />
                <el-option label="湿度" value="humidity" />
                <el-option label="气压" value="pressure" />
                <el-option label="光照强度" value="lightIntensity" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="温度范围">
              <el-slider
                v-model="filters.temperatureRange"
                range
                :min="-20"
                :max="50"
                :step="1"
                show-stops
                show-input
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="湿度范围">
              <el-slider
                v-model="filters.humidityRange"
                range
                :min="0"
                :max="100"
                :step="5"
                show-stops
                show-input
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="数据聚合">
              <el-select v-model="filters.aggregation">
                <el-option label="原始数据" value="raw" />
                <el-option label="每分钟平均" value="minute" />
                <el-option label="每小时平均" value="hour" />
                <el-option label="每日平均" value="day" />
<<<<<<< HEAD
=======
                <el-option label="每月平均" value="month" />
                <el-option label="自动" value="auto" />
>>>>>>> 8812a9148e94551207e748afbba84869577bb3db
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item>
              <el-button type="primary" @click="applyFilters" :loading="loading">
                <el-icon><Search /></el-icon>
                查询数据
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="stats-section">
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon temperature">
              <el-icon><Sunny /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">平均温度</div>
              <div class="stat-value">{{ formatNumber(statistics.avgTemperature) }}°C</div>
              <div class="stat-range">
                {{ formatNumber(statistics.minTemperature) }}°C ~ {{ formatNumber(statistics.maxTemperature) }}°C
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon humidity">
              <el-icon><Cloudy /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">平均湿度</div>
              <div class="stat-value">{{ formatNumber(statistics.avgHumidity) }}%</div>
              <div class="stat-range">
                {{ formatNumber(statistics.minHumidity) }}% ~ {{ formatNumber(statistics.maxHumidity) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon pressure">
              <el-icon><Compass /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">平均气压</div>
              <div class="stat-value">{{ formatPressure(statistics.avgPressure) }}</div>
              <div class="stat-range">
                {{ formatPressure(statistics.minPressure) }} ~ {{ formatPressure(statistics.maxPressure) }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon light">
              <el-icon><Sunny /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">数据总数</div>
              <div class="stat-value">{{ statistics.totalCount }}</div>
              <div class="stat-range">{{ formatTimeRange() }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表展示 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :span="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <span>历史数据趋势图</span>
              <div class="chart-controls">
                <el-radio-group v-model="chartConfig.type" size="small">
                  <el-radio-button label="line">折线图</el-radio-button>
                  <el-radio-button label="bar">柱状图</el-radio-button>
                  <el-radio-button label="scatter">散点图</el-radio-button>
                  <el-radio-button label="heatmap">热力图</el-radio-button>
                </el-radio-group>
                <el-checkbox-group v-model="chartConfig.series" size="small" style="margin-left: 15px">
                  <el-checkbox label="temperature">温度</el-checkbox>
                  <el-checkbox label="humidity">湿度</el-checkbox>
                  <el-checkbox label="pressure">气压</el-checkbox>
                  <el-checkbox label="lightIntensity">光照</el-checkbox>
                </el-checkbox-group>
                <el-button-group style="margin-left: 15px">
                  <el-button size="small" @click="toggleFullscreen">
                    <el-icon><FullScreen /></el-icon>
                    全屏
                  </el-button>
                  <el-button size="small" @click="downloadChart">
                    <el-icon><Download /></el-icon>
                    下载图表
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>
          <div class="chart-container" :class="{ fullscreen: isFullscreen }">
            <v-chart 
              ref="historyChart" 
              :option="chartOption" 
              :loading="chartLoading"
              autoresize
              @click="handleChartClick"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-row :gutter="20" class="table-section">
      <el-col :span="24">
        <el-card class="table-card" shadow="hover">
          <template #header>
            <div class="table-header">
              <span>历史数据列表</span>
              <div class="table-controls">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索数据..."
                  size="small"
                  style="width: 200px"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                <el-button size="small" @click="refreshTableData">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
                <el-button size="small" @click="batchDelete" :disabled="selectedRows.length === 0">
                  <el-icon><Delete /></el-icon>
                  批量删除
                </el-button>
              </div>
            </div>
          </template>
          <el-table 
            ref="dataTable"
            :data="filteredTableData" 
            :loading="tableLoading"
            stripe
            border
            height="500"
            @selection-change="handleSelectionChange"
            @sort-change="handleSortChange"
            @row-click="handleRowClick"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="ID" width="80" sortable />
            <el-table-column prop="temperature" label="温度(°C)" width="120" sortable>
              <template #default="{ row }">
                <span :style="{ color: getTemperatureColor(row.temperature) }">
                  {{ formatNumber(row.temperature) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="humidity" label="湿度(%)" width="120" sortable>
              <template #default="{ row }">
                <span :style="{ color: getHumidityColor(row.humidity) }">
                  {{ formatNumber(row.humidity) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="pressure" label="气压(hPa)" width="140" sortable>
              <template #default="{ row }">
                <span :style="{ color: getPressureColor(row.pressure) }">
                  {{ formatPressure(row.pressure) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="lightIntensity" label="光照强度(lux)" width="140" sortable>
              <template #default="{ row }">
                <span :style="{ color: getLightColor(row.lightIntensity) }">
                  {{ row.lightIntensity }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="记录时间" min-width="180" sortable>
              <template #default="{ row }">
                {{ timeUtils.format(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="数据质量" width="100">
              <template #default="{ row }">
                <el-tag :type="getDataQualityType(row)" size="small">
                  {{ getDataQualityText(row) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button size="small" type="text" @click="viewDetail(row)">
                  详情
                </el-button>
                <el-button size="small" type="text" @click="compareData(row)">
                  对比
                </el-button>
                <el-button size="small" type="text" @click="analyzeData(row)">
                  分析
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="table-pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[20, 50, 100, 200]"
              :total="totalCount"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

<<<<<<< HEAD
=======
    <!-- 调试面板 -->
    <el-row :gutter="20" class="debug-section" v-if="showDebugPanel">
      <el-col :span="24">
        <el-card class="debug-card" shadow="hover">
          <template #header>
            <div class="debug-header">
              <span>调试信息</span>
              <div class="debug-controls">
                <el-switch
                  v-model="showDebugPanel"
                  active-text="显示调试面板"
                  inactive-text="隐藏调试面板"
                />
                <el-button size="small" type="primary" @click="addTestData">
                  添加测试数据
                </el-button>
                <el-button size="small" type="warning" @click="testDatabaseConnection">
                  测试数据库
                </el-button>
                <el-button size="small" @click="clearDebugLogs">
                  清空日志
                </el-button>
              </div>
            </div>
          </template>
          <div class="debug-content">
            <el-tabs>
              <el-tab-pane label="API请求">
                <div class="api-status">
                  <p><strong>最近API请求状态:</strong> {{ sensorStore.loading ? '加载中...' : '空闲' }}</p>
                  <p v-if="sensorStore.error"><strong>错误信息:</strong> <span style="color: red">{{ sensorStore.error }}</span></p>
                </div>
                <div class="api-logs">
                  <h4>API请求日志:</h4>
                  <pre>{{ JSON.stringify(debugLogs, null, 2) }}</pre>
                </div>
              </el-tab-pane>
              <el-tab-pane label="数据状态">
                <div class="store-state">
                  <p><strong>历史数据条数:</strong> {{ sensorStore.historicalData?.length || 0 }}</p>
                  <p><strong>最新数据:</strong> {{ sensorStore.latestData ? '已加载' : '未加载' }}</p>
                  <p><strong>小时数据条数:</strong> {{ sensorStore.hourlyData?.length || 0 }}</p>
                  <p><strong>每日数据条数:</strong> {{ sensorStore.dailyData?.length || 0 }}</p>
                  <p><strong>每月数据条数:</strong> {{ sensorStore.monthlyData?.length || 0 }}</p>
                  <p><strong>当前聚合类型:</strong> {{ sensorStore.aggregationType }}</p>
                </div>
                <div class="data-sample">
                  <h4>数据样本 (最多5条):</h4>
                  <pre>{{ JSON.stringify(sensorStore.historicalData?.slice(0, 5), null, 2) }}</pre>
                  <h4>数据字段检查:</h4>
                  <div v-if="sensorStore.historicalData?.length > 0">
                    <p><strong>时间字段:</strong> 
                      {{ checkDataField(['createdAt', 'time', 'hour', 'date', 'month']) }}
                    </p>
                    <p><strong>温度字段:</strong> 
                      {{ checkDataField(['temperature', 'avgTemperature', 'avgTemp']) }}
                    </p>
                    <p><strong>湿度字段:</strong> 
                      {{ checkDataField(['humidity', 'avgHumidity']) }}
                    </p>
                    <p><strong>气压字段:</strong> 
                      {{ checkDataField(['pressure', 'avgPressure', 'avgPress']) }}
                    </p>
                    <p><strong>光照字段:</strong> 
                      {{ checkDataField(['lightIntensity', 'avgLightIntensity', 'avgLight']) }}
                    </p>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-card>
      </el-col>
    </el-row>

>>>>>>> 8812a9148e94551207e748afbba84869577bb3db
    <!-- 数据详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="数据详情"
      width="800px"
      :before-close="handleDetailClose"
    >
      <div class="detail-content" v-if="selectedData">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="数据ID">{{ selectedData.id }}</el-descriptions-item>
              <el-descriptions-item label="记录时间">{{ timeUtils.format(selectedData.createdAt) }}</el-descriptions-item>
              <el-descriptions-item label="温度">{{ selectedData.temperature }}°C</el-descriptions-item>
              <el-descriptions-item label="湿度">{{ selectedData.humidity }}%</el-descriptions-item>
              <el-descriptions-item label="气压">{{ selectedData.pressure }} Pa</el-descriptions-item>
              <el-descriptions-item label="光照强度">{{ selectedData.lightIntensity }} lux</el-descriptions-item>
              <el-descriptions-item label="数据质量" :span="2">
                <el-tag :type="getDataQualityType(selectedData)">
                  {{ getDataQualityText(selectedData) }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="数据可视化" name="chart">
            <div class="detail-charts">
              <div class="detail-chart">
                <h4>温度</h4>
                <v-chart :option="getDetailChartOption('temperature', selectedData.temperature, '°C')" />
              </div>
              <div class="detail-chart">
                <h4>湿度</h4>
                <v-chart :option="getDetailChartOption('humidity', selectedData.humidity, '%')" />
              </div>
              <div class="detail-chart">
                <h4>气压</h4>
                <v-chart :option="getDetailChartOption('pressure', selectedData.pressure / 100, 'hPa')" />
              </div>
              <div class="detail-chart">
                <h4>光照强度</h4>
                <v-chart :option="getDetailChartOption('light', selectedData.lightIntensity, 'lux')" />
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="历史对比" name="compare">
            <div class="compare-content">
              <p>与前一条数据对比：</p>
              <el-table :data="comparisonData" border>
                <el-table-column prop="metric" label="指标" />
                <el-table-column prop="current" label="当前值" />
                <el-table-column prop="previous" label="前一值" />
                <el-table-column prop="change" label="变化" />
                <el-table-column prop="changePercent" label="变化率" />
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="exportSelectedData">导出数据</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 数据对比对话框 -->
    <el-dialog
      v-model="compareDialogVisible"
      title="数据对比"
      width="1000px"
      :before-close="handleCompareClose"
    >
      <div class="compare-dialog-content">
        <div class="compare-selector">
          <el-form :model="compareForm" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="对比数据1">
                  <el-select v-model="compareForm.data1" placeholder="选择数据">
                    <el-option 
                      v-for="item in recentData" 
                      :key="item.id" 
                      :label="`${item.id} - ${timeUtils.format(item.createdAt)}`" 
                      :value="item.id" 
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="对比数据2">
                  <el-select v-model="compareForm.data2" placeholder="选择数据">
                    <el-option 
                      v-for="item in recentData" 
                      :key="item.id" 
                      :label="`${item.id} - ${timeUtils.format(item.createdAt)}`" 
                      :value="item.id" 
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="compare-result" v-if="compareResult">
          <v-chart :option="compareChartOption" height="400px" />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="compareDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="performCompare">开始对比</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh, Search, Download, Delete, FullScreen,
  Sunny, Cloudy, Compass
} from '@element-plus/icons-vue'
import VChart from 'vue-echarts'
import { useSensorStore } from '@/stores/sensor'
import { timeUtils, numberUtils, colorUtils, dataUtils } from '@/utils'
import { sensorChartConfigs, createGaugeChartOption } from '@/utils/charts'
import { api } from '@/api/request'

// 存储
const sensorStore = useSensorStore()

// 响应式数据
const loading = ref(false)
const chartLoading = ref(false)
const tableLoading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(50)
const totalCount = ref(0)
const selectedRows = ref([])
const detailDialogVisible = ref(false)
const compareDialogVisible = ref(false)
const selectedData = ref(null)
const activeTab = ref('basic')
const isFullscreen = ref(false)
const historyChart = ref(null)
const dataTable = ref(null)
const showDebugPanel = ref(true)
const debugLogs = ref([])

// 筛选器
const filters = reactive({
  timeRange: '24h',
  startTime: '',
  endTime: '',
  dataType: ['temperature', 'humidity', 'pressure', 'lightIntensity'],
  temperatureRange: [-20, 50],
  humidityRange: [0, 100],
  aggregation: 'auto'
})

// 图表配置
const chartConfig = reactive({
  type: 'line',
  series: ['temperature', 'humidity', 'pressure', 'lightIntensity']
})

// 对比表单
const compareForm = reactive({
  data1: null,
  data2: null
})

const compareResult = ref(null)

// 计算属性
const hasData = computed(() => {
  return sensorStore.historicalData && sensorStore.historicalData.length > 0
})

const statistics = computed(() => {
  const data = sensorStore.historicalData || []
  if (data.length === 0) {
    return {
      totalCount: 0,
      avgTemperature: 0,
      minTemperature: 0,
      maxTemperature: 0,
      avgHumidity: 0,
      minHumidity: 0,
      maxHumidity: 0,
      avgPressure: 0,
      minPressure: 0,
      maxPressure: 0
    }
  }
  
  const temperatures = data.map(item => item.temperature).filter(v => v != null)
  const humidities = data.map(item => item.humidity).filter(v => v != null)
  const pressures = data.map(item => item.pressure).filter(v => v != null)
  
  return {
    totalCount: data.length,
    avgTemperature: temperatures.reduce((a, b) => a + b, 0) / temperatures.length || 0,
    minTemperature: Math.min(...temperatures) || 0,
    maxTemperature: Math.max(...temperatures) || 0,
    avgHumidity: humidities.reduce((a, b) => a + b, 0) / humidities.length || 0,
    minHumidity: Math.min(...humidities) || 0,
    maxHumidity: Math.max(...humidities) || 0,
    avgPressure: pressures.reduce((a, b) => a + b, 0) / pressures.length || 0,
    minPressure: Math.min(...pressures) || 0,
    maxPressure: Math.max(...pressures) || 0
  }
})

const filteredTableData = computed(() => {
  let data = sensorStore.historicalData || []
  
  // 应用搜索关键词
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    data = data.filter(item => 
      item.id.toString().includes(keyword) ||
      item.temperature.toString().includes(keyword) ||
      item.humidity.toString().includes(keyword) ||
      timeUtils.format(item.createdAt).toLowerCase().includes(keyword)
    )
  }
  
  // 应用数据类型筛选
  if (filters.dataType.length < 4) {
    data = data.filter(item => {
      return filters.dataType.some(type => item[type] != null)
    })
  }
  
  // 应用温度范围筛选
  data = data.filter(item => 
    item.temperature >= filters.temperatureRange[0] && 
    item.temperature <= filters.temperatureRange[1]
  )
  
  // 应用湿度范围筛选
  data = data.filter(item => 
    item.humidity >= filters.humidityRange[0] && 
    item.humidity <= filters.humidityRange[1]
  )
  
  totalCount.value = data.length
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return data.slice(start, end)
})

const recentData = computed(() => sensorStore.historicalData || [])

const chartOption = computed(() => {
  const data = sensorStore.historicalData || []
  console.log('图表数据更新，数据长度:', data.length)
  
  if (!data || data.length === 0) {
    console.log('没有历史数据，显示空图表')
    return {
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center',
        textStyle: { color: '#999', fontSize: 16 }
      }
    }
  }
  
  // 检查数据类型，根据聚合类型处理数据
  const aggregationType = sensorStore.aggregationType
  console.log('当前聚合类型:', aggregationType)
  
  // 验证和格式化数据
  try {
    const isValidData = dataUtils.validateDataset(data)
    if (!isValidData) {
      addDebugLog('error', { message: '数据验证失败，无法渲染图表' })
      console.error('数据验证失败，无法渲染图表')
      return {
        title: {
          text: '数据格式错误',
          left: 'center',
          top: 'center',
          textStyle: { color: '#f56c6c', fontSize: 16 }
        }
      }
    }
    
    // 格式化数据
    let formattedData
    
    if (aggregationType === 'hourly') {
      // 小时数据格式化
      formattedData = data.map(item => ({
        time: item.hour || item.time,
        temperature: item.avgTemperature || item.avgTemp,
        humidity: item.avgHumidity,
        pressure: item.avgPressure || item.avgPress,
        lightIntensity: item.avgLightIntensity || item.avgLight
      }))
    } else if (aggregationType === 'daily') {
      // 日数据格式化
      formattedData = data.map(item => ({
        time: item.date,
        temperature: item.avgTemperature || item.avgTemp,
        humidity: item.avgHumidity,
        pressure: item.avgPressure || item.avgPress,
        lightIntensity: item.avgLightIntensity || item.avgLight
      }))
    } else if (aggregationType === 'monthly') {
      // 月数据格式化
      formattedData = data.map(item => ({
        time: item.month,
        temperature: item.avgTemperature || item.avgTemp,
        humidity: item.avgHumidity,
        pressure: item.avgPressure || item.avgPress,
        lightIntensity: item.avgLightIntensity || item.avgLight
      }))
    } else {
      // 原始数据格式化
      formattedData = dataUtils.formatDataset(data)
    }
    
    console.log('格式化后的数据:', formattedData)
    console.log('图表类型:', chartConfig.type)
    console.log('选中的数据系列:', chartConfig.series)
    
    let option;
    switch (chartConfig.type) {
      case 'line':
        option = sensorChartConfigs.multiSeries(formattedData, chartConfig.series)
        break
      case 'bar':
        option = sensorChartConfigs.bar(formattedData, chartConfig.series)
        break
      case 'scatter':
        option = sensorChartConfigs.scatter(formattedData)
        break
      case 'heatmap':
        option = sensorChartConfigs.heatmap(formattedData)
        break
      default:
        option = sensorChartConfigs.combined(formattedData)
    }
    
    console.log('生成的图表配置:', option)
    return option
  } catch (err) {
    console.error('生成图表配置出错:', err)
    return {
      title: {
        text: '图表生成错误',
        left: 'center',
        top: 'center',
        textStyle: { color: '#f56c6c', fontSize: 16 }
      }
    }
  }
})

const comparisonData = computed(() => {
  if (!selectedData.value) return []
  
  const current = selectedData.value
  const data = sensorStore.historicalData || []
  const currentIndex = data.findIndex(item => item.id === current.id)
  
  if (currentIndex <= 0) return []
  
  const previous = data[currentIndex - 1]
  
  return [
    {
      metric: '温度',
      current: `${current.temperature}°C`,
      previous: `${previous.temperature}°C`,
      change: `${(current.temperature - previous.temperature).toFixed(1)}°C`,
      changePercent: `${(((current.temperature - previous.temperature) / previous.temperature) * 100).toFixed(1)}%`
    },
    {
      metric: '湿度',
      current: `${current.humidity}%`,
      previous: `${previous.humidity}%`,
      change: `${(current.humidity - previous.humidity).toFixed(1)}%`,
      changePercent: `${(((current.humidity - previous.humidity) / previous.humidity) * 100).toFixed(1)}%`
    },
    {
      metric: '气压',
      current: `${(current.pressure / 100).toFixed(0)} hPa`,
      previous: `${(previous.pressure / 100).toFixed(0)} hPa`,
      change: `${((current.pressure - previous.pressure) / 100).toFixed(0)} hPa`,
      changePercent: `${(((current.pressure - previous.pressure) / previous.pressure) * 100).toFixed(1)}%`
    },
    {
      metric: '光照强度',
      current: `${current.lightIntensity} lux`,
      previous: `${previous.lightIntensity} lux`,
      change: `${current.lightIntensity - previous.lightIntensity} lux`,
      changePercent: `${(((current.lightIntensity - previous.lightIntensity) / previous.lightIntensity) * 100).toFixed(1)}%`
    }
  ]
})

const compareChartOption = computed(() => {
  if (!compareResult.value) return {}
  
  const { data1, data2 } = compareResult.value
  
  return {
    title: {
      text: '数据对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['数据1', '数据2'],
      top: 30
    },
    radar: {
      indicator: [
        { name: '温度', max: 50 },
        { name: '湿度', max: 100 },
        { name: '气压', max: 1100 },
        { name: '光照强度', max: 2000 }
      ]
    },
    series: [{
      type: 'radar',
      data: [
        {
          value: [data1.temperature, data1.humidity, data1.pressure / 100, data1.lightIntensity],
          name: '数据1',
          itemStyle: { color: '#1890ff' }
        },
        {
          value: [data2.temperature, data2.humidity, data2.pressure / 100, data2.lightIntensity],
          name: '数据2',
          itemStyle: { color: '#f5222d' }
        }
      ]
    }]
  }
})

// 方法
const formatNumber = (value, decimals = 1) => {
  return numberUtils.format(value, decimals)
}

const formatPressure = (pressure) => {
  if (!pressure) return '--'
  return `${numberUtils.format(pressure / 100, 0)} hPa`
}

const formatTimeRange = () => {
  if (filters.timeRange === 'custom' && filters.startTime && filters.endTime) {
    return `${timeUtils.format(filters.startTime, 'MM-DD HH:mm')} ~ ${timeUtils.format(filters.endTime, 'MM-DD HH:mm')}`
  }
  
  const rangeMap = {
    '1h': '最近1小时',
    '6h': '最近6小时',
    '12h': '最近12小时',
    '24h': '最近24小时',
    '3d': '最近3天',
    '7d': '最近7天',
    '30d': '最近30天',
    '3m': '最近3个月',
    '6m': '最近6个月',
    '1y': '最近1年'
  }
  
  return rangeMap[filters.timeRange] || '未知范围'
}

const getTemperatureColor = (temp) => colorUtils.getTemperatureColor(temp)
const getHumidityColor = (humidity) => colorUtils.getHumidityColor(humidity)
const getPressureColor = (pressure) => colorUtils.getPressureColor(pressure)
const getLightColor = (light) => colorUtils.getLightColor(light)

const getDataQualityType = (data) => {
  const hasAllData = data.temperature && data.humidity && data.pressure && data.lightIntensity
  if (!hasAllData) return 'danger'
  
  const isReasonable = 
    data.temperature >= -50 && data.temperature <= 80 &&
    data.humidity >= 0 && data.humidity <= 100 &&
    data.pressure >= 80000 && data.pressure <= 120000 &&
    data.lightIntensity >= 0 && data.lightIntensity <= 2000
  
  return isReasonable ? 'success' : 'warning'
}

const getDataQualityText = (data) => {
  const type = getDataQualityType(data)
  const textMap = {
    success: '良好',
    warning: '异常',
    danger: '缺失'
  }
  return textMap[type] || '未知'
}

const getDetailChartOption = (type, value, unit) => {
  const colors = {
    temperature: '#f5222d',
    humidity: '#1890ff',
    pressure: '#52c41a',
    light: '#faad14'
  }
  
  return createGaugeChartOption({
    title: '',
    value: value,
    min: 0,
    max: type === 'temperature' ? 50 : type === 'humidity' ? 100 : type === 'pressure' ? 1100 : 2000,
    unit: unit,
    thresholds: [{ min: 0, max: 999999, color: colors[type] }]
  })
}

const resetFilters = () => {
  Object.assign(filters, {
    timeRange: '24h',
    startTime: '',
    endTime: '',
    dataType: ['temperature', 'humidity', 'pressure', 'lightIntensity'],
    temperatureRange: [-20, 50],
    humidityRange: [0, 100],
    aggregation: 'auto'
  })
  applyFilters()
}

const handleTimeRangeChange = () => {
  if (filters.timeRange !== 'custom') {
    filters.startTime = ''
    filters.endTime = ''
    applyFilters()
  }
}

const applyFilters = async () => {
  loading.value = true
  chartLoading.value = true
  
  try {
    let hours = 24
    
    if (filters.timeRange === 'custom') {
      if (!filters.startTime || !filters.endTime) {
        ElMessage.warning('请选择开始时间和结束时间')
        loading.value = false
        chartLoading.value = false
        return
      }
      // 使用自定义时间范围获取数据
      console.log('获取自定义时间范围数据:', filters.startTime, filters.endTime)
      addDebugLog('fetchDataByTimeRange', { startTime: filters.startTime, endTime: filters.endTime })
      await sensorStore.fetchDataByTimeRange(filters.startTime, filters.endTime)
    } else {
      // 解析时间范围
      const rangeMap = {
        '1h': 1,
        '6h': 6,
        '12h': 12,
        '24h': 24,
        '3d': 72,
        '7d': 168,
        '30d': 720,
        '3m': 2160,   // 90天
        '6m': 4320,   // 180天
        '1y': 8760    // 365天
      }
      hours = rangeMap[filters.timeRange] || 24
      
      console.log('获取数据, 时间范围:', filters.timeRange, '小时数:', hours)
      
      // 使用自动聚合API，根据时间范围自动选择聚合级别
      if (filters.aggregation === 'auto') {
        console.log('使用自动聚合模式')
        addDebugLog('fetchAutoAggregatedData', { hours })
        await sensorStore.fetchAutoAggregatedData(hours)
        // 更新UI显示当前聚合模式
        const aggregationTypeText = {
          hourly: '按小时聚合',
          daily: '按天聚合',
          monthly: '按月聚合'
        }
        ElMessage.info(`已自动选择${aggregationTypeText[sensorStore.aggregationType] || '原始数据'}模式`)
      }
      // 对于超过7天的数据查询，强制使用聚合模式
      else if (hours > 168 && filters.aggregation === 'raw') {  // 7天 = 168小时
        console.log('时间范围超过7天，自动切换为每日统计')
        ElMessage.info(`时间范围超过7天，已自动切换为每日统计数据`)
        filters.aggregation = 'day'
      }
      
      if (filters.aggregation === 'hour') {
        console.log('获取小时平均数据')
        // 对于长时间范围，使用天数而不是小时数
        let days = Math.ceil(hours / 24)
        if (filters.timeRange === '3m' || filters.timeRange === '6m' || filters.timeRange === '1y') {
          addDebugLog('fetchHourlyAverageData', { days })
          await sensorStore.fetchHourlyAverageData(days)
        } else {
          addDebugLog('fetchHourlyAverageData', { hours: Math.ceil(hours / 24) })
          await sensorStore.fetchHourlyAverageData(Math.ceil(hours / 24))
        }
      } else if (filters.aggregation === 'day') {
        console.log('获取每日统计数据')
        // 对于长时间范围，直接使用月份计算天数
        let days = Math.ceil(hours / 24)
        if (filters.timeRange === '3m') {
          days = 90
        } else if (filters.timeRange === '6m') {
          days = 180
        } else if (filters.timeRange === '1y') {
          days = 365
        }
        addDebugLog('fetchDailyStatistics', { days })
        await sensorStore.fetchDailyStatistics(days)
      } else if (filters.aggregation === 'month') {
        console.log('获取每月统计数据')
        // 计算月数
        let months = Math.ceil(hours / 720) // 假设每月30天
        if (months > 12) months = 12 // 最多查询12个月
        addDebugLog('fetchMonthlyStatistics', { months })
        await sensorStore.fetchMonthlyStatistics(months)
      } else if (filters.aggregation !== 'auto') {
        console.log('获取原始历史数据')
        addDebugLog('fetchHistoricalData', { hours })
        await sensorStore.fetchHistoricalData(hours)
      }
    }
    
    // 打印获取到的数据
    console.log('获取到的历史数据:', sensorStore.historicalData)
    console.log('历史数据长度:', sensorStore.historicalData?.length || 0)
    addDebugLog('dataReceived', { 
      count: sensorStore.historicalData?.length || 0,
      success: true
    })
    
    currentPage.value = 1
  } catch (error) {
    console.error('获取数据失败:', error)
    addDebugLog('error', { message: error.message || '获取数据失败' })
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
    chartLoading.value = false
  }
}

const exportData = () => {
  const data = sensorStore.historicalData || []
  if (data.length === 0) {
    ElMessage.warning('暂无数据可导出')
    return
  }
  
  const csvContent = [
    ['ID', '时间', '温度(°C)', '湿度(%)', '气压(Pa)', '光照强度(lux)'],
    ...data.map(item => [
      item.id,
      timeUtils.format(item.createdAt),
      item.temperature,
      item.humidity,
      item.pressure,
      item.lightIntensity
    ])
  ].map(row => row.join(',')).join('\n')
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `history_data_${timeUtils.format(new Date(), 'YYYY-MM-DD_HH-mm-ss')}.csv`
  link.click()
  
  ElMessage.success('数据导出成功')
}

const refreshTableData = async () => {
  tableLoading.value = true
  try {
    await applyFilters()
  } catch (error) {
    ElMessage.error('刷新数据失败')
  } finally {
    tableLoading.value = false
  }
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSortChange = ({ column, prop, order }) => {
  console.log('排序变化:', { column, prop, order })
}

const handleRowClick = (row) => {
  viewDetail(row)
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const viewDetail = (data) => {
  selectedData.value = data
  activeTab.value = 'basic'
  detailDialogVisible.value = true
}

const compareData = (data) => {
  compareForm.data1 = data.id
  compareDialogVisible.value = true
}

const analyzeData = (data) => {
  ElMessage.info('数据分析功能开发中...')
}

const batchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条数据吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用删除API
    ElMessage.success('删除成功')
    await refreshTableData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleDetailClose = () => {
  detailDialogVisible.value = false
  selectedData.value = null
}

const handleCompareClose = () => {
  compareDialogVisible.value = false
  compareForm.data1 = null
  compareForm.data2 = null
  compareResult.value = null
}

const exportSelectedData = () => {
  if (!selectedData.value) return
  
  const data = selectedData.value
  const csvContent = [
    ['字段', '值'],
    ['ID', data.id],
    ['温度(°C)', data.temperature],
    ['湿度(%)', data.humidity],
    ['气压(Pa)', data.pressure],
    ['光照强度(lux)', data.lightIntensity],
    ['记录时间', timeUtils.format(data.createdAt)]
  ].map(row => row.join(',')).join('\n')
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `sensor_data_${data.id}.csv`
  link.click()
  
  ElMessage.success('数据导出成功')
}

const performCompare = () => {
  if (!compareForm.data1 || !compareForm.data2) {
    ElMessage.warning('请选择两个要对比的数据')
    return
  }
  
  const data = sensorStore.historicalData || []
  const data1 = data.find(item => item.id === compareForm.data1)
  const data2 = data.find(item => item.id === compareForm.data2)
  
  if (!data1 || !data2) {
    ElMessage.error('找不到对比数据')
    return
  }
  
  compareResult.value = { data1, data2 }
  ElMessage.success('对比完成')
}

const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
  if (isFullscreen.value) {
    document.documentElement.requestFullscreen?.()
  } else {
    document.exitFullscreen?.()
  }
}

const downloadChart = () => {
  if (!historyChart.value) {
    ElMessage.warning('图表未加载完成')
    return
  }
  
  const canvas = historyChart.value.getEchartsInstance().getConnectedDataURL({
    type: 'png',
    backgroundColor: '#fff'
  })
  
  const link = document.createElement('a')
  link.href = canvas
  link.download = `chart_${timeUtils.format(new Date(), 'YYYY-MM-DD_HH-mm-ss')}.png`
  link.click()
  
  ElMessage.success('图表下载成功')
}

const handleChartClick = (params) => {
  console.log('图表点击:', params)
  // 这里可以实现点击图表数据点的交互逻辑
}

const addDebugLog = (action, details) => {
  debugLogs.value.unshift({
    time: new Date().toLocaleTimeString(),
    action,
    details
  })
  
  // 最多保留20条日志
  if (debugLogs.value.length > 20) {
    debugLogs.value = debugLogs.value.slice(0, 20)
  }
}

const clearDebugLogs = () => {
  debugLogs.value = []
}

// 监听器
watch(() => chartConfig.type, () => {
  chartLoading.value = true
  setTimeout(() => {
    chartLoading.value = false
  }, 500)
})

watch(() => chartConfig.series, () => {
  chartLoading.value = true
  setTimeout(() => {
    chartLoading.value = false
  }, 300)
})

// 生命周期
onMounted(async () => {
  try {
    // 检查是否已登录
    const token = localStorage.getItem('token')
    if (!token) {
      // 如果没有令牌，尝试使用默认账号登录
      addDebugLog('auth', { message: '未检测到认证令牌，尝试自动登录' })
      await autoLogin()
    } else {
      addDebugLog('auth', { message: '检测到认证令牌，继续加载数据' })
    }
    
    // 获取数据
    await applyFilters()
  } catch (error) {
    ElMessage.error('初始化失败')
    addDebugLog('error', { message: error.message || '初始化失败' })
  }
})

// 自动登录函数
const autoLogin = async () => {
  try {
    addDebugLog('login', { username: 'admin', message: '尝试自动登录' })
    
    // 调用登录API
    const response = await fetch('/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: 'admin',
        password: 'admin123'
      })
    })
    
    const data = await response.json()
    
    if (data.success && data.token) {
      localStorage.setItem('token', data.token)
      localStorage.setItem('username', 'admin')
      addDebugLog('login', { success: true, message: '自动登录成功' })
    } else {
      addDebugLog('login', { success: false, message: data.message || '自动登录失败' })
      ElMessage.warning('自动登录失败，请手动登录')
    }
  } catch (error) {
    addDebugLog('login', { success: false, message: error.message || '自动登录失败' })
    console.error('自动登录失败:', error)
  }
}

// 添加测试数据
const addTestData = async () => {
  try {
    addDebugLog('addTestData', { message: '开始添加测试数据' })
    ElMessage.info('正在添加测试数据，请稍候...')
    
    // 生成过去30天的测试数据，每小时一条
    const now = new Date()
    const testData = []
    
    // 生成过去30天的数据，每小时一条
    for (let i = 0; i < 30 * 24; i++) {
      const timestamp = new Date(now.getTime() - i * 60 * 60 * 1000) // 每小时一条
      
      // 根据时间生成模拟数据
      const hour = timestamp.getHours()
      const day = timestamp.getDate()
      
      // 温度：白天高，夜间低，有随机波动
      const baseTemp = 20 + Math.sin((hour - 12) / 12 * Math.PI) * 10
      const temperature = baseTemp + Math.random() * 4 - 2
      
      // 湿度：夜间高，白天低，有随机波动
      const baseHumidity = 60 - Math.sin((hour - 12) / 12 * Math.PI) * 20
      const humidity = baseHumidity + Math.random() * 10 - 5
      
      // 气压：随机波动
      const pressure = 101300 + Math.random() * 1000 - 500
      
      // 光照：白天有，夜间无，有随机波动
      let lightIntensity = 0
      if (hour >= 6 && hour <= 18) {
        // 白天，光照随时间变化，中午最强
        lightIntensity = 1000 * Math.sin((hour - 6) / 12 * Math.PI) + Math.random() * 200
      }
      
      testData.push({
        temperature,
        humidity,
        pressure,
        lightIntensity: Math.max(0, Math.round(lightIntensity)),
        createdAt: timestamp.toISOString()
      })
    }
    
    // 批量添加测试数据
    const response = await api.post('/sensors/batch-add', testData)
    
    if (response.success) {
      ElMessage.success(`成功添加 ${response.count || testData.length} 条测试数据`)
      addDebugLog('addTestDataSuccess', { count: response.count || testData.length })
      
      // 重新加载数据
      await applyFilters()
    } else {
      ElMessage.error('添加测试数据失败')
      addDebugLog('addTestDataError', { message: response.message })
    }
  } catch (error) {
    console.error('添加测试数据失败:', error)
    addDebugLog('addTestDataError', { message: error.message || '添加测试数据失败' })
    ElMessage.error('添加测试数据失败')
  }
}

// 检查数据字段
const checkDataField = (fields) => {
  if (!sensorStore.historicalData || sensorStore.historicalData.length === 0) {
    return '无数据';
  }
  
  const sample = sensorStore.historicalData[0];
  const existingFields = fields.filter(field => sample[field] !== undefined);
  
  if (existingFields.length === 0) {
    return '未找到字段';
  }
  
  return existingFields.join(', ');
}

// 测试数据库连接
const testDatabaseConnection = async () => {
  try {
    addDebugLog('testDatabaseConnection', { message: '开始测试数据库连接' })
    ElMessage.info('正在测试数据库连接，请稍候...')
    
    const result = await sensorStore.testDatabaseConnection()
    
    if (result) {
      addDebugLog('databaseTestResult', { 
        totalCount: result.totalCount,
        hasLatestData: result.hasLatestData,
        recentHourCount: result.recentHourCount,
        recentDayCount: result.recentDayCount,
        hourlyDataCount: result.hourlyDataCount,
        dailyDataCount: result.dailyDataCount,
        monthlyDataCount: result.monthlyDataCount
      })
      
      // 显示测试结果
      ElMessageBox.alert(
        `
        <div>
          <p><strong>数据库连接:</strong> ${result.dbConnection}</p>
          <p><strong>总数据量:</strong> ${result.totalCount}</p>
          <p><strong>最新数据:</strong> ${result.hasLatestData ? '有' : '无'}</p>
          <p><strong>最近1小时数据量:</strong> ${result.recentHourCount}</p>
          <p><strong>最近1天数据量:</strong> ${result.recentDayCount}</p>
          <p><strong>小时聚合数据量:</strong> ${result.hourlyDataCount}</p>
          <p><strong>日聚合数据量:</strong> ${result.dailyDataCount}</p>
          <p><strong>月聚合数据量:</strong> ${result.monthlyDataCount}</p>
        </div>
        `,
        '数据库测试结果',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定'
        }
      )
      
      // 如果没有数据，提示添加测试数据
      if (result.totalCount === 0) {
        ElMessageBox.confirm(
          '数据库中没有数据，是否要添加测试数据？',
          '提示',
          {
            confirmButtonText: '添加测试数据',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          addTestData()
        }).catch(() => {})
      }
    } else {
      ElMessage.error('数据库测试失败，请查看控制台输出')
    }
  } catch (error) {
    console.error('数据库测试失败:', error)
    addDebugLog('databaseTestError', { message: error.message || '数据库测试失败' })
    ElMessage.error('数据库测试失败')
  }
}
</script>

<style scoped>
.history {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  font-size: 16px;
  color: #606266;
  margin-bottom: 20px;
}

/* 筛选器样式 */
.filter-card {
  margin-bottom: 20px;
  border: none;
  border-radius: 12px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.filter-form {
  margin-top: 15px;
}

/* 统计卡片样式 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stat-icon.temperature {
  background: linear-gradient(135deg, #f5222d, #fa541c);
}

.stat-icon.humidity {
  background: linear-gradient(135deg, #1890ff, #096dd9);
}

.stat-icon.pressure {
  background: linear-gradient(135deg, #52c41a, #389e0d);
}

.stat-icon.light {
  background: linear-gradient(135deg, #faad14, #d48806);
}

.stat-info {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-range {
  font-size: 12px;
  color: #909399;
}

/* 图表样式 */
.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  border: none;
  border-radius: 12px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  flex-wrap: wrap;
  gap: 15px;
}

.chart-controls {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.chart-container {
  height: 500px;
  transition: all 0.3s ease;
}

.chart-container.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  background: white;
}

/* 表格样式 */
.table-section {
  margin-bottom: 20px;
}

.table-card {
  border: none;
  border-radius: 12px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  flex-wrap: wrap;
  gap: 10px;
}

.table-controls {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.table-pagination {
  margin-top: 20px;
  text-align: center;
}

/* 对话框样式 */
.detail-content {
  max-height: 600px;
  overflow-y: auto;
}

.detail-charts {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.detail-chart {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
}

.detail-chart h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #606266;
  text-align: center;
}

.compare-content {
  margin-top: 15px;
}

.compare-dialog-content {
  max-height: 600px;
  overflow-y: auto;
}

.compare-selector {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.compare-result {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
}

/* 调试面板样式 */
.debug-section {
  margin-bottom: 20px;
}

.debug-card {
  border: none;
  border-radius: 12px;
}

.debug-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.debug-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.debug-content {
  padding: 20px;
}

.api-status {
  margin-bottom: 10px;
}

.api-logs {
  margin-top: 10px;
}

.store-state {
  margin-bottom: 10px;
}

.data-sample {
  margin-top: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .history {
    padding: 10px;
  }
  
  .page-header h1 {
    font-size: 24px;
  }
  
  .page-header p {
    font-size: 14px;
  }
  
  .chart-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .chart-controls {
    justify-content: center;
  }
  
  .table-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .table-controls {
    justify-content: center;
  }
  
  .stat-content {
    padding: 15px;
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }
  
  .stat-value {
    font-size: 20px;
  }
  
  .chart-container {
    height: 300px;
  }
  
  .detail-charts {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .filter-form .el-col {
    margin-bottom: 15px;
  }
  
  .chart-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .chart-controls > * {
    margin-bottom: 10px;
  }
}

/* 自定义下拉菜单样式 */
:deep(.time-range-dropdown) {
  max-height: 400px !important;
  overflow-y: auto !important;
}

/* 确保下拉菜单完全显示 */
:deep(.el-select-dropdown__list) {
  padding-bottom: 8px;
  max-height: none !important;
}
</style>